<?php

namespace App\ApiBackend\Admin;

use App\Domains\UserDao;
use App\Http\Controllers\ApiBaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

/**
 *  用户密码
 */
class Password extends ApiBaseController
{


  /**
   * 参数检查
   */
  protected function check(): void
  {
    try {
      request()->validate([
        //'adminId' => 'required',
        'password' => 'required',
      ]);
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = "预检: " . $exception->getMessage();
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $adminId = \request('adminId') ?? \request()->user()->adminId;

    //数据
    $updateData = [
      "password" => Hash::make(\request('password')),
      "updateTime" => date('Y-m-d H:i:s'),
    ];
    //更新数据
    try {
      if (\request('passwordOld'))
      {//检测密码是否正确
        $password = DB::table('admin')->where('adminId', $adminId)->value('password');
        if (!Hash::check(\request('passwordOld'), $password)) {
          throw new \Exception('原密码输入错误');
        }
      }
      DB::table('admin')->where('adminId', $adminId)->update($updateData);
      $this->result["message"] = "修改密码成功";
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] =  $exception->getMessage();
    }
    return;

  }
}
